package org.study.shardingsphere.boot.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.driver.api.yaml.YamlShardingSphereDataSourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;

import javax.sql.DataSource;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

/**
 * @author lenovo
 */
@Slf4j
@Configuration
public class DataSourceConfig {
    @Bean("dataSource")
    public DataSource dataSource() throws Exception {
        // 分别读取配置文件
        String dsYaml = Files.readString(ResourceUtils.getFile("classpath:sharding-ds.yaml").toPath(), StandardCharsets.UTF_8);
        String ruleYaml = Files.readString(ResourceUtils.getFile("classpath:sharding-rule.yaml").toPath(), StandardCharsets.UTF_8);
        // 合并成一个配置文件：简单拼接即可
        String fullYaml = dsYaml + System.lineSeparator() + ruleYaml;
        // 创建DataSource
        return YamlShardingSphereDataSourceFactory.createDataSource(fullYaml.getBytes(StandardCharsets.UTF_8));
    }
}